package org.batatasframework.web.method.resolver;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.core.MethodParameter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;

import cn.bonoon.kernel.security.LogonUser;

public abstract class AbstractArgumentResolver implements HandlerMethodArgumentResolver, BeanFactoryAware, InitializingBean{

	protected ConfigurableBeanFactory beanFactory;
	
	@Override
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		if (beanFactory instanceof ConfigurableBeanFactory) {
			this.beanFactory = (ConfigurableBeanFactory) beanFactory;
		}
	}

	@Override
	public void afterPropertiesSet() throws Exception { }

	protected LogonUser getUser() {
		LogonUser user = null;
		
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (null != authentication) {
			Object principal = authentication.getPrincipal();
			if(principal instanceof LogonUser){
				user = (LogonUser)principal;
			}
		}
		return user;
	}

	protected Object unsupported(MethodParameter parameter){
		throw new UnsupportedOperationException("Unknown parameter type: " + parameter.getParameterType() + " in method: " + parameter.getMethod());
	}

}
